# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
租户信息表服务类
----------------------------------------------------
@Project :   xinhou-openai-framework
@File    :   Tenant.py
@Contact :   sp_hrz@qq.com

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/04/16 22:04  peng.shen   v1.0.0     None
"""

from sqlalchemy.orm import Session

from common.entity.Tenant import Tenant
from xinhou_openai_framework.core.cache.CacheManager import CacheManager
from xinhou_openai_framework.core.orm.service.BaseServiceImpl import BaseServiceImpl
from xinhou_openai_framework.utils.DateUtil import DateUtil
from xinhou_openai_framework.utils.IdUtil import IdUtil
from xinhou_openai_framework.utils.ObjDictUtil import ObjectDict


class TenantService(BaseServiceImpl[Tenant]):
    """
    租户服务类
    """

    def __init__(self, db: Session = None):
        super(TenantService, self).__init__(db, Tenant)

    def register(self, model: Tenant):
        model.api_key = IdUtil.uuid_32()  # 生成UUID作为api_key
        model.update_by = "admin"
        model.updated_at = DateUtil.get_current_datetime()
        model.create_by = "admin"
        model.created_at = DateUtil.get_current_datetime()
        return self.save(model)

    def get_cache_tenant(self, model: Tenant):
        cache = CacheManager.get_instance()
        cache_tenant_id = f"tenant_{model.id}"
        tenant = cache.get(cache_tenant_id)
        return ObjectDict().from_dict(tenant)
